from uuid import uuid4
import json
import os
from datetime import datetime
from django.db.models import Q

from rest_framework import serializers

from .models import *
from apps import redis_client
from apps.products.models import ProductModel
from apps.order.models import OrderModel
from apps.devices.models import DevicesModel
from util.exception import ValidationError
from django.conf import settings


class ProductOrderListSerializer(serializers.ModelSerializer):
    order_key = serializers.CharField(max_length=50, allow_null=False, allow_blank=False)
    product_name = serializers.CharField(max_length=200, allow_null=True, allow_blank=True)
    product_number = serializers.CharField(max_length=200, allow_null=True, allow_blank=True)

    class Meta:
        model = ProductOrderModel
        fields = ["order_key", "product_name", "product_number"]


class ProductOrderListTempSerializer(serializers.ModelSerializer):
    order_key = serializers.CharField(max_length=50, allow_null=False, allow_blank=False)

    class Meta:
        model = ProductOrderModel
        fields = ["order_key"]


class orderproductCreateSerializer(serializers.ModelSerializer):
    order_key = serializers.CharField(max_length=50, allow_null=False, allow_blank=False)
    product_number = serializers.CharField(max_length=200, allow_null=True, allow_blank=True)
    product_sum = serializers.IntegerField(allow_null=False)

    class Meta:
        model = ProductOrderModel
        fields = ["product_sum", "product_number", "order_key"]

    def create(self, validata):
        order_key = validata.get("order_key")
        product_number = validata.get("product_number")
        product_sum = validata.get("product_sum")
        product = ProductModel.objects.filter(product_number=product_number).first()
        if product:
            orderproduct = ProductOrderModel.objects.filter(product_number=product_number).first()
            if orderproduct:
                if orderproduct.product_sum > product_sum:
                    raise ValidationError(40001)
                orderproduct.product_sum = product_sum
                o_p_id = orderproduct.id
                orderproduct.save()
            else:
                product_key = product.id
                product_name = product.product_name
                id = str(uuid4()).replace("-", "")
                o_p_id = id
                data = {
                    "id": id,
                    "order_key": order_key,
                    "product_key": product_key,
                    "product_name": product_name,
                    "product_number": product_number,
                    "product_sum": product_sum
                }
                ProductOrderModel.objects.create(**data)
            p = ProductOrderModel.objects.filter(id=o_p_id).first()
            product_number = p.product_number
            product_name = p.product_name
            product_sum = p.product_sum
            order_id = p.order_id
            ds = DevicesModel.objects.filter(product_number=product_number).all()
            ne_ad = product_sum - len(ds)
            if ne_ad <= 0:
                ne_ad = 0
            for i in range(ne_ad):
                id = str(uuid4()).replace("-", "")
                data = {
                    "id": id,
                    "product_name": product_name,
                    "product_number": product_number,
                    "order_id": order_id,
                }
                DevicesModel.objects.create(**data)
        else:
            raise ValidationError(20001)


class orderproductCreateListSerializer(serializers.ModelSerializer):
    orderproductids = serializers.DictField(allow_null=True)

    class Meta:
        model = ProductOrderModel
        fields = ["orderproductids"]

    def create(self, validata):
        validata = validata.get("orderproductids")
        orderproductids = validata.get("orderproductids")
        order_key = validata.get("order_key")[0]
        order_id = OrderModel.objects.filter(id=order_key).first().order_id
        r_datas = redis_client.hgetall(order_key)
        datas = []
        for key, value in r_datas.items():
            d = json.loads(value)
            if d.get("key") in orderproductids:
                datas.append({
                    "key": d.get("key"),
                    "product_number": d.get("product_number"),
                    "product_name": d.get("product_name"),
                    "product_sum": d.get("product_sum")
                })
        for data in datas:
            product_key = self.__create_product(data)
            self.__create_productorder(order_key, product_key, data)
            self.__create_device(order_id, data)

    def __create_product(self, data):
        p = ProductModel.objects.filter(product_number=data.get("product_number")).first()
        if p:
            product_key = p.id
        else:
            id = str(uuid4()).replace("-", "")
            product_key = id
            ProductModel.objects.create(**{
                "id": product_key,
                "product_number": data.get("product_number"),
                "product_name": data.get("product_name")
            })
        return product_key

    def __create_productorder(self, order_key, product_key, data):
        p_o = ProductOrderModel.objects.filter(product_number=data.get("product_number")).first()
        if p_o:
            p_o.product_sum = data.get("product_sum")
        else:
            ProductOrderModel.objects.create(**{
                "id": data.get("id"),
                "order_key": order_key,
                "product_key": product_key,
                "product_name": data.get("product_name"),
                "product_number": data.get("product_number"),
                "product_sum": data.get("product_sum")
            })

    def __create_device(self, order_id, data):
        product_number = data.get("product_number")
        product_sum = data.get("product_sum")
        product_name = data.get("product_name")
        ds = DevicesModel.objects.filter(product_number=product_number).all()
        ne_ad = int(product_sum) - len(ds)
        if ne_ad <= 0:
            ne_ad = 0
        for i in range(ne_ad):
            id = str(uuid4()).replace("-", "")
            data = {
                "id": id,
                "product_name": product_name,
                "product_number": product_number,
                "order_id": order_id,
            }
            DevicesModel.objects.create(**data)
